import * as comm from '../../../utils/common';
const storageService = require('../../../services/storage');
// 设备信息页面
const appInstance = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    otaAvailable: false,
    latestFirmware: '',
    isUpdating: false,
    updateProgress: 0,
    showUpdateModal: false,
    showUpdateProgressModal: false,

    did: null,
    device: null,
    temperature: 0,
    deviceVer: 'Vx.x.x',
    imagePath: null,
    imgName: null,
    host: "www.99666666.xyz",
    port: 80,
    activateDate: '--------',
    rtcErr: false,
    showReset: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options && options.did) {
      this.data.did = options.did
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'error',
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
      return
    }

    // 设置导航栏标题为空白
    wx.setNavigationBarTitle({
      title: ''
    })

    // 设置导航栏为暗色
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#121212',
      animation: {
        duration: 300,
        timingFunc: 'easeIn'
      }
    })

    // 检查固件更新
    //this.checkOTAStatus()
    this.setData({
      showReset: !appInstance.globalData.isRelease
    })
    if (appInstance.globalData.isRelease) {
      let $t = this
      comm.httpGet("/device/getActiveDate?id=" + this.data.did, function (res) {
        if (!comm.isEmpty(res.data)) {
          $t.setData({
            activateDate: res.data
          })
        }
      })
    }
  },

  /**
   * 检查固件更新状态
   */
  /*
  checkOTAStatus: function () {
    // 模拟从服务器获取OTA更新信息
    // 实际应用中，这里应该调用API检查是否有可用的更新
    setTimeout(() => {
      // 随机模拟是否有更新，50%的概率有更新
      const hasUpdate = Math.random() >= 0.5

      if (hasUpdate) {
        this.setData({
          otaAvailable: true,
          latestFirmware: 'v1.1.0'
        })
      }
    }, 1000)
  },*/

  /**
   * 检查固件更新
   */
  checkFirmwareUpdate: function () {
    wx.showLoading({
      title: '检查更新中...',
      mask: true
    })

    let $t = this;
    comm.httpGet("/version/check?ver=" + $t.data.device.deviceVer, function (res) {
      wx.hideLoading()
      //res.data = "test.bin"
      if (comm.isEmpty(res.data)) {
        // 显示已是最新版本提示
        wx.showToast({
          title: '已是最新版本',
          icon: 'success'
        })
      } else {
        $t.setData({
          showUpdateModal: true,
          imgName: res.data
        })
        // 显示发现更新提示
        wx.showToast({
          title: '有新固件可用',
          icon: 'success',
          duration: 2000
        });
      }
    }, function (error) {
      console.log(error);
      wx.showToast({
        title: '检查更新异常！',
        icon: 'none'
      })
    });
  },

  /**
   * 确认更新
   */
  confirmUpdate: function () {
    this.setData({
      showUpdateModal: false
    })
    //this.startOTAUpdate()
    appInstance.sendMtMsg(this.data.device.topicSend, "updateImg", {
      host: this.data.host,
      port: this.data.port,
      image: this.data.imgName
    }, function (error) {
      if (error) {
        wx.showToast({
          title: '发送更新固件命令失败!' + error,
          icon: 'none'
        })
      } else {
        wx.showModal({
          title: 'OTA升级提示',
          content: '已发送固件更新命令,请等待设备更新和重启!'
        });
      }
    });
  },

  /**
   * 取消更新
   */
  cancelUpdate: function () {
    this.setData({
      showUpdateModal: false
    })
  },

  resetDevice() {
    const $t = this
    wx.showModal({
      title: '重置设备',
      content: '重置设备将使设备恢复初始化，确认要重置设备吗？',
      success: res => {
        if (res.confirm) {
          appInstance.sendMtMsg($t.data.device.topicSend, "reset", null, function (error) {
            if (error) {
              wx.showToast({
                title: '发送重置命令失败!' + error,
                icon: 'none'
              })
            } else {
              wx.showToast({
                title: '发送重置命令成功!',
                icon: 'none'
              })
            }
          });
        }
      },
    })
  },

  /**
   * 开始OTA更新
   */
  /*
  startOTAUpdate: function () {
    this.setData({
      showUpdateProgressModal: true,
      isUpdating: true,
      updateProgress: 0
    })
    

    // 模拟更新进度
    this.updateProgressAnimation()
  },*/

  /**
   * 模拟更新进度动画
   */
  /*
  updateProgressAnimation: function () {
    const that = this
    let progress = 0
    const timer = setInterval(() => {
      progress += Math.floor(Math.random() * 5) + 1
      if (progress >= 100) {
        progress = 100
        clearInterval(timer)

        // 更新完成后
        setTimeout(() => {
          that.setData({
            isUpdating: false,
            deviceInfo: {
              ...that.data.deviceInfo,
              firmwareVersion: that.data.latestFirmware
            }
          })
        }, 500)
      }

      that.setData({
        updateProgress: progress
      })
    }, 200)
  },
  */

  /**
   * 关闭更新进度弹窗
   */
  /*
  closeUpdateProgressModal: function () {
    this.setData({
      showUpdateProgressModal: false
    })
  },*/

  /**
   * 返回上一页
   */
  navigateBack: function () {
    wx.navigateBack()
  },

  /**
   * 跳转到设备配置页
   */
  /*
  navigateToDeviceConfig: function () {
    wx.navigateTo({
      url: '/pages/device_config/device_config?deviceId=' + this.data.deviceInfo.id
    })
  },*/

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log("device_info onShow...")
    const $t = this;
    wx.$event.on("status", this, (obj) => {
      $t.chgStatus(obj)
    });
    wx.$event.on("EventOnline", this, (obj) => {
      $t.changeOnline(1, obj);
    });
    wx.$event.on("EventOffline", this, (obj) => {
      $t.changeOnline(0, obj);
    });
    const device = storageService.getDeviceInfo(this.data.did)
    wx.$event.on(device.topicSub, this, (obj) => {
      if (obj.type == "rtc") {
        console.log("rtc result:", obj)
        if (obj.msg == "rtc not online") {
          $t.setData({
            rtcErr: true
          })
        }
      }
    });
    device.online = appInstance.checkIsOnline(device.topicSub) ? 1 : 0
    const temperature = appInstance.getTemperature(device.topicSub)
    if (temperature !== -99) {
      device.temperature = temperature
    }
    this.setData({
      device: device,
      temperature: parseInt((device.temperature + "").replace(">", "")),
      imagePath: '/images/devices/' + device.deviceType + '.svg',
      deviceVer: "V" + device.deviceVer.substring(1)
    })
    appInstance.sendMtMsg(device.topicSend, "rtc", null);
  },
  onHide: function () {
    console.log("device_info onHide...")
    wx.$event.remove("status", this);
    wx.$event.remove("EventOnline", this);
    wx.$event.remove("EventOffline", this);
    wx.$event.remove(this.data.device.topicSub, this);
  },


  chgStatus(obj) {
    if (this.data.device.topicSub !== obj.topic) {
      return
    }
    if (obj.msg.tempNow !== this.data.device.temperature) {
      this.setData({
        ['device.temperature']: obj.msg.tempNow,
        temperature: parseInt((obj.msg.tempNow + "").replace(">", ""))
      })
    }
  },
  changeOnline(isOnline, topic) {
    if (this.data.device.topicSub !== topic) {
      return
    }
    this.setData({
      ['device.online']: isOnline
    })
  },



})